﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using SiteUnity.Layers.Application;

namespace SiteUnity.Frame.Modules
{
    [DefaultProperty("TrackerID")]
    [ToolboxData("<{0}:GoogleAnalytics runat=server></{0}:GoogleAnalytics>")]
    public class GoogleAnalytics : WebControl
    {
        public string TrackerID { get; set; }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (string.IsNullOrEmpty(TrackerID))
                TrackerID = SiteManager.FindWebsiteSettingByKey("GoogleAnalytics-TrackerID").Value;
        }

        private string analyticsCode = @"var _gaq = _gaq || [];
                                          _gaq.push(['_setAccount', '{0}']);
                                          _gaq.push(['_trackPageview']);

                                          (function() {
                                            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                                            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                                            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
                                          })();";

        protected override void RenderContents(HtmlTextWriter output)
        {
            Page.ClientScript.RegisterStartupScript(typeof(Page), "readyGoogleAnalytics", analyticsCode.Replace("{0}", TrackerID), true);
        }
    }
}
